import type { UserState } from "./store.types";
import { acceptHMRUpdate } from "pinia";

import { currentApi, loginApi, logoutApi } from "~/api";
import { userStorage } from "~/composables/storage";

const useUserStore = defineStore("userStore", () => {
    const state: UserState = reactive(
        userStorage.value || {
            token: "", // 登录token
            info: {} // 用户信息
        }
    );

    const current = ref<Stick.TCurrentStoreModel>({
        isLogin: false
    });

    function tokenChange(token: string) {
        state.token = token;
    }
    function infoChange(info: Objable) {
        state.info = info;
    }

    // login by login.vue
    async function login(params: { name: string; password: string; isMd5?: boolean }) {
        const res = await loginApi(
            params.name,
            params.isMd5 ? params.password : stickUtils.toMd5(params.password)
        );

        if (res.success) {
            tokenChange(res.data.token);
            infoChange({
                isLogin: true,
                ...res.data
            });
            current.value = {
                isLogin: true,
                ...res.data
            };
        }
        return res;
    }
    // get user info after user logined
    async function getInfo(params: { token: string }) {
        const { code, data } = await $api.post<any>("/user/info", params);
        if (code === 200) {
            infoChange(data.info);
            return data.info;
        }
        return null;
    }

    async function loadUserInfo() {
        const res = await currentApi();
        if (res.success) {
            infoChange({
                isLogin: true,
                ...res.data
            });
            current.value = {
                isLogin: true,
                ...res.data
            };
        }
        return res;
    }

    // login out the system after user click the logout button
    async function logout() {
        await logoutApi();

        globalStorage.value = null;
        userStorage.value = null;
        tabsStorage.value = [];
        location.reload();
    }

    const clear = () => {
        globalStorage.value = null;
        userStorage.value = null;
        tabsStorage.value = [];
        current.value = {
            isLogin: false
        };
        tokenChange("");
        infoChange({});
        location.reload();
    };

    return {
        ...toRefs(state),
        current,
        clear,
        loadUserInfo,
        tokenChange,
        infoChange,
        login,
        getInfo,
        logout
    };
});

useUserStore(piniaInit).$subscribe((_mutation, state) => {
    userStorage.value = state;
});

export default useUserStore;
export const userStoreWithout = () => useUserStore(piniaInit);

if (import.meta.hot) {
    import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot));
}
